﻿using SqlSugar;

namespace Bigway.Common.Services.Repositories;

public class BaseRepository<TEntity>(ISqlSugarClient db) : IBaseRepository<TEntity>
    where TEntity : class, new()
{
    protected readonly ISqlSugarClient Db = db;

    protected ISugarQueryable<TEntity> Queryable => Db.Queryable<TEntity>();
    protected IUpdateable<TEntity> Updatable => Db.Updateable<TEntity>();

    public Task<List<TEntity>> GetAllAsync(CancellationToken token = default)
    {
        return Queryable.ToListAsync(token);
    }

    public Task<List<TEntity>> GetAllAsync(
        Func<ISugarQueryable<TEntity>, ISugarQueryable<TEntity>> filter,
        CancellationToken token = default)
    {
        var query = filter(Queryable);
        return query.ToListAsync(token);
    }

    public virtual async Task AddAllAsync(List<TEntity> entities, CancellationToken token = default)
    {
        await Db.Insertable(entities).ExecuteCommandAsync(token);
    }

    public virtual async Task<TEntity> AddAsync(TEntity entity, CancellationToken token = default)
    {
        await Db.Insertable(entity).ExecuteCommandAsync(token);
        return entity;
    }

    public virtual async Task UpdateAsync(TEntity entity, CancellationToken token = default)
    {
        await Db.Updateable(entity).ExecuteCommandAsync(token);
    }

    public async Task UpdateAllAsync(List<TEntity> entities, CancellationToken token = default)
    {
        await Db.Updateable(entities).ExecuteCommandAsync(token);
    }

    public async Task DeleteAsync(TEntity entity, CancellationToken token = default)
    {
        await Db.Deleteable(entity).ExecuteCommandAsync(token);
    }

    public async Task DeleteAllAsync(List<TEntity> entities, CancellationToken token = default)
    {
        await Db.Deleteable(entities).ExecuteCommandAsync(token);
    }
}